function R = megTrainOneVsRest(T,L,varargin)
% input: T - traindata trialsXfeatures,
%        L - Labels (arbitrary)
%        optional: featselect - your featureselction method 
%                   C - regular.Param (default: [] see Joachims)
%                   balance - balance trainset (default:false)

param = args2Param(varargin);

% create classifier pairs
R.classes = unique(L);
nClasses = length(R.classes);


R.feat_bin = cell(nClasses,1);
R.W = cell(nClasses,1);
R.b0 = zeros(nClasses,1);

for k=1:nClasses;
    curIdx = true(length(L),1);
    curLabel = double(L(curIdx)==R.classes(k)) - ...
                double(L(curIdx)~=R.classes(k));
    if param.doBalance,
        labelIdx = getBalancedTrainset(curLabel);
        curLabel=curLabel(labelIdx);
        curIdx(curIdx) = curIdx(curIdx)&labelIdx;
        %        fprintf('%i %i\n',sum(curLabel<0),sum(curLabel>0));
    end
    if isfield(param,'featselect') && ~strcmpi(param.featselect,'none'),
        % do feature selection
        if strcmpi(param.featselect,'CSP'),
            Treshaped = reshape(T(curIdx,:)',[param.reshape.reSize,sum(curIdx)]);
            R.csp{k}.W=megCSPEstimate(Treshaped,curLabel);
            [varDat,filtDat ]=megCSPApply(Treshaped,R.csp{k}.W,param.nSpatialFilter);
            if strcmpi(param.cspFeat, 'filter'),
                [curTrain R.csp{k}.reshapeParam] = megReshapeTrain(filtDat);
            else
                [curTrain R.csp{k}.reshapeParam] = megReshapeTrain(varDat);
            end
        else
            % do some different featureselection
            curTrain = T(curIdx,R.feat_bin{k});
        end
    else
        R.feat_bin{k} = true(1,size(T,2));        
        curTrain=T(curIdx,:);
    end
    
    % train spider alg
    alg=svm;
    alg.optimizer='libsvm';
    if isempty(param.C),
        % determine default C according to Joachims
        alg.C=ecogGetDefC(curTrain);
    elseif ~isnumeric(param.C),
        alg.C = getDefC(TRAIN)*str2double(param.C);
    else
        alg.C=param.C;
    end
    alg.algorithm.verbosity=0;
    d = data(curTrain,curLabel);
    [tr res_alg] = train(alg,d);
    R.W{k} = get_w(res_alg);
    R.b0(k) = res_alg.b0;
end

function param = args2Param(args)

% set default values
param.doBalance = false;

k=1;
while k<length(args),
    if ischar(args{k}),
        if strcmpi('param',args{k}),
            tmp=args{k+1};
            fNames=fieldnames(tmp);
            for p=1:length(fNames),
                eval(['param.' fNames{p} '=tmp.' fNames{p} ';'] );
            end
        end
        if strcmpi('c',args{k}),
            param.C=args{k+1};
        end
        if strcmpi('balance',args{k}),
            param.doBalance=args{k+1};
        end
        if strcmpi('featselect',args{k}),
            param.featselect=args{k+1};
        end
    else
        error('argument name must be a string');
    end
    k=k+2;
end

function labelIdx = getBalancedTrainset(L)
% labelIdx = getBalancedTrainset(L)
% L - labels [-1 1]
% returns binary vector labelIdx of size(L)

idx{1}=find(L>0);
idx{2}=find(L<0);
[n minCond]=min([length(idx{1}) length(idx{2})]);
randIdx=randperm(length(idx{3-minCond}));
L(idx{3-minCond}(setdiff(1:length(idx{3-minCond}),randIdx(1:n))))=0;
labelIdx=L~=0;
